<template>
  <div>
    <el-container>
      <el-header style="padding: 0px;display:flex;justify-content:space-between;align-items: center">
        <div style="display: inline">
          <el-select @change="refresh" v-model="storeId" size="mini" placeholder="请选择">
            <el-option
              v-for="store in stores"
              :key="store.value"
              :label="store.label"
              :value="store.value">
            </el-option>
          </el-select>
          <el-input
            placeholder="通过会员卡号查询会员清单,记得回车哦..."
            clearable
            style="width: 300px;margin: 0px;padding: 0px;"
            size="mini"
            @change="refresh"
            @keyup.enter.native="searchByCardNo"
            prefix-icon="el-icon-search"
            v-model="cardNumber">
          </el-input>
          <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search" @click="searchByCardNo">查询</el-button>
        </div>
      </el-header>
      <el-main style="padding-left: 0px;padding-top: 0px">
        <el-row>
          <el-col :span="4" style="text-align: left;">
            <span style="font-size:larger;font-weight: bold;">消费清单</span>
          </el-col>
          <el-col :span="20" style="text-align: left;">
            <span style="font-size: 12px;font-weight: bold">余额: {{balance}}</span>
            <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-plus" @click="showExpendView">消费</el-button>
            <el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-plus" @click="showRechargeView">充值</el-button>
          </el-col>
        </el-row>
        <div style="margin-top: 10px">
          <el-table
            :data="items"
            v-loading="tableLoading"
            border
            stripe
            size="mini"
          >
            <el-table-column
              prop="storeName"
              width="200"
              align="left"
              label="门店">
            </el-table-column>
            <el-table-column
              prop="itemName"
              width="200"
              align="left"
              label="消费项">
            </el-table-column>
            <el-table-column
              width="150"
              align="left"
              label="金额">
              <template slot-scope="scope">
                <span>{{(scope.row.consumeMoney / 100).toFixed(2) }} 元</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="consumeTime"
              width="220"
              align="left"
              label="时间">
            </el-table-column>
          </el-table>
          <div style="display: flex;justify-content: space-between;margin: 2px">
            <el-pagination
              background
              :page-size="10"
              :current-page="currentPage"
              @current-change="currentChange"
              layout="prev, pager, next"
              :total="totalCount">
            </el-pagination>
          </div>
        </div>
        <el-dialog title="消费清单" :visible.sync="expendFormVisible">
          <el-form :model="total" ref="expendForm">
            <template v-for="(item, index) in total.items">
              <el-form-item :key="'item_' + index"  :prop="'items.' + index + '.itemId'" :rules="[{ required: true, message: '必选:服务项', trigger: 'blur'}]" label="服务项" :label-width="formLabelWidth">
                <el-select v-model="item.itemId" @change="autoWriteItemPrice(index)" placeholder="请选择服务项">
                  <el-option
                    v-for="option in itemOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value">
                  </el-option>
                </el-select>
                <el-button style="margin-left: 5px;" type="danger" size="mini" @click="dropItemByIndex(index)">删除</el-button>
              </el-form-item>
              <el-form-item :key="'item_price_'+index" :prop="'items.' + index + '.consumeMoney'" :rules="[{ required: true, message: '必填:金额', trigger: 'blur'}, {pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message:'必须为金额类型(保留两位小数)'}]" label="金额" :label-width="formLabelWidth">
                <el-input style="width: 217px;" @change="count" v-model="item.consumeMoney" auto-complete="off">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </template>
            <el-form-item>
              <el-button type="primary" size="mini" @click="addItem">添加服务项</el-button>
            </el-form-item>
            <template v-for="(medicine, index) in total.medicines">
              <el-form-item :key="'medicine_' + index" :prop="'medicines.' + index + '.itemId'" :rules="[{ required: true, message: '必选:药品项', trigger: 'blur'}]" label="药品项目" :label-width="formLabelWidth">
                <el-select @change="autoWriteMedicinePrice(index)" v-model="medicine.itemId" placeholder="请选择药品项">
                  <el-option
                    v-for="option in medicineOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value">
                  </el-option>
                </el-select>
                <el-button style="margin-left: 5px;" type="danger" size="mini" @click="dropMedicineByIndex(index)">删除</el-button>
              </el-form-item>
              <el-form-item :key="'medicine_price_'+index" :prop="'medicines.' + index + '.consumeMoney'" :rules="[{ required: true, message: '必填:金额', trigger: 'blur'}, {pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message:'必须为金额类型(保留两位小数)'}]" label="金额" :label-width="formLabelWidth">
                <el-input style="width: 217px;" @change="count" v-model="medicine.consumeMoney" auto-complete="off">
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </template>
            <el-form-item v-if="total.items || total.items.length > 0">
              <el-button type="primary" size="mini" @click="addMedicine">添加药品项</el-button>
            </el-form-item>
            <el-form-item label="合计金额" :label-width="formLabelWidth">
              <div style="text-align: left">
                <span style="font-weight: bold;font-size: large">{{account}} 元</span>
              </div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="expend">确 定</el-button>
            <el-button @click="expendFormVisible = false">取 消</el-button>
          </div>
        </el-dialog>
        <el-dialog title="充值" :visible.sync="rechargeFormVisible">
          <el-form :model="rechargeData" ref="rechargeForm">
            <el-form-item label="会员卡号" :label-width="formLabelWidth">
              <div style="text-align: left">
                <span>{{cardNumber}}</span>
              </div>
            </el-form-item>
            <el-form-item label="充值金额" prop="rechargeMoney" :rules="[{ required: true, message: '必选:充值金额', trigger: 'blur'}, {pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message:'必须为金额类型(保留两位小数)'}]" :label-width="formLabelWidth">
              <el-input style="width: 217px;" v-model="rechargeData.rechargeMoney" auto-complete="off">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="recharge">确 定</el-button>
            <el-button @click="rechargeFormVisible = false">取 消</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        flag: false,
        expendFormVisible: false,
        rechargeFormVisible: false,
        storeId: '',
        stores: [],
        cardNumber: '',
        rechargeData: {
          rechargeMoney:'',
        },
        account: 0,
        items: [],
        total: {
          items: [],
          medicines: []
        },
        itemOptions: [],
        medicineOptions: [],
        formLabelWidth: '120px',
        totalCount: -1,
        currentPage: 1,
        tableLoading: false,
        balance:0.00 //余额
      }
    },
    mounted: function () {
      let _this = this;
      this.stores = this.$store.state.stores.map(item => {
        let result = {};
        result.value=item.storeId;
        result.label=item.storeName
        return result;
      })
    },
    methods: {
      addItem: function () {
        this.total.items.push({
          consumeMoney: 0,
          itemId: ''
        })
      },
      addMedicine: function () {
        this.total.medicines.push({
          consumeMoney: 0,
          itemId: ''
        })
      },
      currentChange(currentChange){
        this.currentPage = currentChange;
        this.searchByCardNo();
      },
      searchByCardNo: function () {
        let _this = this;
        if (this.cardNumber && this.storeId) {
          this.tableLoading = true;
          this.postJsonRequest('/order/consume/query/list/cardNumber?pageSize=10&pageNum=' + this.currentPage, {cardNumber: this.cardNumber, storeId: this.storeId} ).then(resp => {
            _this.tableLoading = false;
            if (resp && resp.status == 200) {
              let data = resp.data;
              this.items = data.result
              this.totalCount = data.total
              this.balance = (data.balance / 100).toFixed(2)
              this.flag = true
            }
          }).catch(error =>{
            _this.tableLoading = false;
          })
          this.getRequest('/consume/query/list/' + this.storeId).then(resp => {
            if (resp && resp.status == 200) {
              _this.itemOptions = [];
              _this.medicineOptions = [];
              if (resp.data.length > 0) {
                let data = resp.data
                data.forEach(function (item, index, array) {
                  if (item.type == '1') {
                    _this.itemOptions.push(item)
                  } else {
                    _this.medicineOptions.push(item)
                  }
                })
              } else {
                _this.itemOptions = [];
                _this.medicineOptions = [];
              }
            }
          })
        } else {
          if(!this.cardNumber){
            this.$message({
              showClose: true,
              message: '请先填写会员卡号',
              type: 'warning'
            });
          } else if (!this.storeId) {
            this.$message({
              showClose: true,
              message: '请先选择商户',
              type: 'warning'
            });
          }
        }

      },
      expend() {
        // 消费接口
        let _this = this;
        this.$refs['expendForm'].validate((valid) => {
          if (valid) {
            let consumeList = this.total.items.concat(this.total.medicines);
            let datalist = []
            consumeList.forEach(function (item, index, array) {
              let temp = Object.assign({}, item)
              temp.consumeMoney = temp.consumeMoney * 100
              datalist.push(temp)
            })
            let params = {
              cardNumber: this.cardNumber,
              consumeList: datalist,
              storeId: this.storeId
            }
            this.postJsonRequest('/order/consume/add/batch', params).then(resp => {
              if (resp && resp.status == 200) {
                _this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                _this.searchByCardNo() //更新余额
                _this.expendFormVisible = false
              }
            })
          }
        })
      },
      recharge() {
        // 充值接口
        let _this = this
        this.$refs['rechargeForm'].validate((valid) => {
          if (valid) {
            this.postJsonRequest('/mbr/card/recharge/record/basic/', {
              cardNo: this.cardNumber,
              balance: (this.rechargeData.rechargeMoney * 100),
              storeId: this.storeId
            }).then(resp => {
              if (resp && resp.status == 200) {
                _this.$message({
                  message: '充值成功',
                  type: 'success'
                });
                _this.searchByCardNo() //更新余额
                _this.rechargeFormVisible = false
              }
            })
          }
        })
      },
      showRechargeView() {
        if (this.storeId == '') {
          this.$message({
            showClose: true,
            message: '请先选择商户',
            type: 'warning'
          });
          return;
        }
        if (this.cardNumber == '') {
          this.$message({
            showClose: true,
            message: '请先填写会员卡号',
            type: 'warning'
          });
          return;
        }
        if (!this.flag) {
          this.$message({
            showClose: true,
            message: '请先查询会员卡号',
            type: 'warning'
          });
          return;
        }
        this.rechargeData.rechargeMoney = ''
        this.rechargeFormVisible = true
      },
      showExpendView() {
        this.account = 0;
        this.total.items = []
        this.total.medicines = []
        if (this.storeId == '') {
          this.$message({
            showClose: true,
            message: '请先选择商户',
            type: 'warning'
          });
          return;
        }
        if (this.cardNumber == '') {
          this.$message({
            showClose: true,
            message: '请先填写会员卡号',
            type: 'warning'
          });
          return;
        }
        if (!this.flag) {
          this.$message({
            showClose: true,
            message: '请先查询会员卡号',
            type: 'warning'
          });
          return;
        }
        this.expendFormVisible = true
      },
      count() {
        let _this = this
        console.log(this.total)
        let account = 0
        this.total.items.forEach(function (item, index, array) {
          account = _this.FloatAdd(item.consumeMoney, account)
        })
        this.total.medicines.forEach(function (medicine, index, array) {
          account = _this.FloatAdd(medicine.consumeMoney, account)
        })
        this.account = account
      },
      FloatAdd (arg1, arg2){
        let r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2));
        return (arg1*m+arg2*m)/m;
      },
      refresh() {
        this.flag = false;
      },
      dropItemByIndex(index) {
        this.total.items.splice(index,1);
        this.count();
      },
      dropMedicineByIndex(index) {
        this.total.medicines.splice(index,1);
        this.count();
      },
      autoWriteItemPrice(index) {
        let itemId = this.total.items[index].itemId
        let n = this.itemOptions.findIndex(function (item, index, array) {
          if(item.value == itemId)
            return true
        })
        this.total.items[index].consumeMoney = this.itemOptions[n].price / 100
        this.count()
      },
      autoWriteMedicinePrice(index) {
        let itemId = this.total.medicines[index].itemId
        let n = this.medicineOptions.findIndex(function (item, index, array) {
          if(item.value == itemId)
            return true
        })
        this.total.medicines[index].consumeMoney = this.medicineOptions[n].price / 100
        this.count()
      }
    }
  }
</script>
<style>
  .el-dialog__body {
    padding-top: 0px;
    padding-bottom: 0px;
  }

  .el-dialog__header {
    text-align: left;
  }

  .el-form-item__content {
    text-align: left;
  }
</style>
